import {
	login,
	getUserInfo,
	zhuce
} from '../../api/login/index.js'


//vuex 
const user = {
	namespaced: true,
	state: {
		//token
		Token: uni.getStorageSync('Token') || {
			access_token: ''
		},

		//用户信息
		UserInfo: uni.getStorageSync('UserInfo') || {},
	},
	mutations: {
		// 授权Authorization
		SET_TOKEN(state, provider) {
			state.Token = provider;
		},
		// 设置个人信息
		SET_USERINFO(state, provider) {
			state.UserInfo = provider;
		},
	},
	actions: {
		// 登录 标记1
		Login({
			commit
		}, userInfo) {
			return new Promise((resolve, reject) => {

				//在这里发送登录请求
				login(userInfo).then(res => {
					resolve(res)
				}).catch(error => {
					reject(error)
				})

			})
		},
		zhuce({
			commit
		}, userInfo) {
			return new Promise((resolve, reject) => {
		
				//在这里发送登录请求
				zhuce(userInfo).then(res => {
					console.log("注册了" + JSON.stringify(res))
					if (res.code == 200) {
		
						//拿到token 把token存起来
						//	commit('SET_TOKEN', res.token);
		
						uni.setStorageSync('SET_TOKEN', res.data.data.usertoken);
						uni.setStorageSync('Token',res.data.data.usertoken);
						//	commit('SET_ISLOGIN', true);
						uni.setStorageSync('SET_ISLOGIN', true);
		
					}
		
					resolve(res)
				}).catch(error => {
					reject(error)
				})
		
			})
		},
		
		// 退出
		Logout({
			commit,
			state
		}) {
			return new Promise((resolve) => {
				logout(state.token).then(() => {
					resolve()
				}).catch(() => {
					resolve()
				}).finally(() => {
					commit('SET_TOKEN', {
						access_token: ''
					});
					//commit('SET_ISLOGIN', false);
					uni.setStorageSync('SET_ISLOGIN', false);
					uni.removeStorageSync('Token');
					uni.removeStorageSync('IsLogin');
				})
			})
		},
		// 获取个人信息 标记2
		GetUserInfo({
			commit,
			state
		}) {
			return new Promise((resolve) => {

				//在这里发送获取用户信息的请求
				getUserInfo().then(res => {
					console.log("获取了用户信息"+JSON.stringify(res))
					if (res.code === 200) {

						//拿到数据后 存vuex
						commit('SET_USERINFO', res.data);
					}
					resolve(res)
				})
			})
		},
		
	}

}

export default user
